﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace HSIA.SMS
{
    public partial class FormSms : Form
    {
        public FormSms(DatabaseObject _dbo)
        {
            dbo = _dbo;
            InitializeComponent();
        }

        private GSMModem Sms = GSMModem.Instance;
        private DatabaseObject dbo;

        private void FormSms_Load(object sender, EventArgs e)
        {
            dgvSms.AutoGenerateColumns = false;

        }

        private void FormSms_Shown(object sender, EventArgs e)
        {
            dgvSms.DataSource = mySms.GetData();
            int balance = WebSms.GetBalance();
            if (balance > 0) SetInfoLbl("可用余额：" + balance, 2, false);
        }

        private void FormSms_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAddSms fas = new FormAddSms();
            if (fas.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] datas = fas.GetData();
                mySms.AddSms(datas[0], datas[1], dbo.sXMLDir);
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewRow dgvr = dgvSms.CurrentRow;
            if (dgvr != null)
            {
                DataRow dr = (dgvr.DataBoundItem as DataRowView).Row;
                dr.Delete();
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 全部发送ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 发送ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewRow dgvr = dgvSms.CurrentRow;
            if (dgvr != null)
            {
                DataRow dr = (dgvr.DataBoundItem as DataRowView).Row;
                Sms_Send(dr);
            }
        }

        private void 余额查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int balance = WebSms.GetBalance();
            if (balance > 0) SetInfoLbl("可用余额：" + balance, 2, true);
        }

        private void SetInfoLbl(string sText, int iIndex, bool bMsgBox)
        {
            ToolStripStatusLabel lbl = null;
            switch (iIndex)
            {
                case 1: lbl = toolStripStatusLabel1; break;
                case 2: lbl = toolStripStatusLabel2; break;
                default:
                    break;
            }
            if (lbl != null) lbl.Text = "   " + sText;
            if (bMsgBox) MessageBox.Show(sText, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void Query()
        {
            throw new NotImplementedException();
        }


        private static FormSms fs;
        public static MySms mySms;
        public static System.Threading.Timer SmsSendThread;
        public static bool bSendIsRun = true; //循环发送标志位
        public static int iInterval = 5 * 60 * 1000;//定时器扫描间隔1h
        public static DataTable dtSendData;//待发送数据


        /// <summary>
        /// 启动定时器
        /// </summary>
        public static void StartSendThread()
        {
            GSMModem.Instance.OnRecieved += new GSMModem.OnRecievedHandler(Sms_OnRecieved);
            //Sms_OnRecieved(null, null);
            SmsSendThread = new System.Threading.Timer(Sms_OnSend, null, 0, iInterval);
        }

        /// <summary>
        /// 短信接收事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Sms_OnRecieved(object sender, EventArgs e)
        {
            try
            {
                string[] sMsg = GSMModem.Instance.ReadNewMsg().Split('$');  //此处引发异常（此处不属于主进程）  须回调函数才能改变此属性
                if (sMsg.Length != 4) return;

                string tel = sMsg[1].TrimStart('8', '6');
                //string sSendUserId = SmsLog.GetKeyByTel(tel);

                //SmsLog model = new SmsLog()
                //{
                //    Type = 0,
                //    Phone = tel,
                //    InputDate = DateTime.Now, //PublicMethod.GetDateTime(sMsg[2].Substring(10)),
                //    SendUserId = sSendUserId,
                //    Info = sMsg[3]
                //};
                //SmsLogDal.Instance.ReceiverSms(model);
            }
            catch (Exception ex)
            {
                GSMModem.Instance.setBalloonTip(ex.Message, "短信接收错误", 3);
            }
            if (fs != null)
            {
                fs.Invoke((EventHandler)delegate
                {
                    fs.Query();
                });
            }
        }

        /// <summary>
        /// 短信发送进程
        /// </summary>
        public static void Sms_OnSend(object sender)
        {
            dtSendData = mySms.GetData();

            if (dtSendData != null && dtSendData.Rows.Count > 0)
            {
                foreach (DataRow dr in dtSendData.Rows)
                {
                    Sms_Send(dr);
                    Thread.Sleep(100);
                }
                if (fs != null)
                {
                    fs.Invoke((EventHandler)delegate
                    {
                        fs.Query();
                    });
                }
            }
        }

        /// <summary>
        /// 委托的短信发送函数
        /// </summary>
        /// <param name="dr"></param>
        public static void Sms_Send(DataRow dr)
        {
            if (dr != null && dr["State"].ToString() != "0")
            {
                string sMsg = dr["Info"].ToString().Trim();
                string sPhone = dr["Phone"].ToString().Trim();
                try
                {
                    dr["State"] = (int)SmsLog.StateType.执行;
                    if (WebSms.SendMsg(sPhone, sMsg) != 0)
                    {
                        dr["Remarks"] = "Web短信发送错误！";
                        //GSMModem.Instance.SendMsg(sPhone, sMsg);
                    }
                    dr["State"] = (int)SmsLog.StateType.完成;
                }
                catch (Exception ex)
                {
                    dr["State"] = (int)SmsLog.StateType.错误;
                    dr["Remarks"] = ex.Message;
                }
                try
                {
                    mySms.SendSmsState(dr["KeyId"].ToString(), PublicMethod.Getbyte(dr["State"]), dr["DB_Conn"].ToString());
                }
                catch (Exception ex)
                {
                    dr["Remarks"] = ex.Message;
                }
            }
        }

        public void SetLbl(string sText, int iIndex, bool bMsgBox)
        {
            if (fs != null)
            {
                fs.Invoke((EventHandler)delegate
                {
                    fs.SetInfoLbl(sText, iIndex, bMsgBox);
                });
            }
        }
    }
}
